import global from '../utils/global'
import { BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { existsSync } from 'fs'
import globalPublic from '../utils/public'

export function initIpcMain() {
  ipcMain.on('start', async () => {
    global.mainWindow?.webContents.send('change-loading', true)
    //获取当前路径
    const pddWorkbenchPath = join(global.localPath, 'pdd', '3.4.0.16', 'PddWorkbench.exe')

    if (existsSync(pddWorkbenchPath)) {
      let cmd = `powershell "Start-Process -FilePath 'Launch.exe' -ArgumentList '${pddWorkbenchPath} PddExtend.dll -use_devtool -js_url https://oss.wengekefu.com/db.js?${new Date().getTime()}' -WorkingDirectory '${global.injectPath}' -WindowStyle Hidden"`
      let success = await globalPublic.executeCommand(cmd)
      if (!success) {
        return
      }
      setTimeout(() => {
        global.mainWindow?.webContents.send('change-loading', false)
      }, 1000 * 3)
    } else {
      console.error(`未找到文件: ${pddWorkbenchPath}`)
      global.mainWindow?.webContents.send('change-loading-text', '拼多多不存在，下载中...')
      await globalPublic.downloadAndUnzip()
    }
  })

  // 窗口拖动事件
  ipcMain.on('dragWindow', (event, { x, y }) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      win.setPosition(x, y)
    }
  })

  // 窗口最小化事件
  ipcMain.on('minWindow', () => {
    global.mainWindow?.minimize()
  })

  // 窗口关闭事件
  ipcMain.on('closeWindow', () => {
    global.mainWindow?.close()
  })

  //窗口置顶/取消置顶事件
  ipcMain.on('toTop', () => {
    global.mainWindow?.setAlwaysOnTop(!global.mainWindow?.isAlwaysOnTop())
  })
}
